#include "main.h"

/*打印查询界面*/
void printf_query(void)
{
	printf("========【欢迎使用本词典】========\n");
	printf("\t输入\t命令\t\n");
	printf("----------------------------------\n");
	printf("\t1\t查询单词\t\n");
	printf("\t2\t查询历史\t\n");
	printf("\t0\t退出\t\n");
	printf("----------------------------------\n");
}


/*查询单词*/
void query_word(int fd,MSG* pmsg)
{
	pmsg->type = 'Q';//命令类型：查询单词
	
	while(1)
	{
		/*输入要查询的单词*/
		printf(">>查询单词：");
		scanf("%s",pmsg->info);
		fflush(stdin);

		if(strncmp(pmsg->info,"##",2) == 0)
		{
			pmsg->type = 'E';//命令类型：退出
			write(fd,pmsg,sizeof(MSG));
			close(fd);
			break;
		}

		/*向服务器发送要查询的单词*/
		write(fd,pmsg,sizeof(MSG));

		/*等待服务器返回查询结果*/
		usleep(300000);
		read(fd,pmsg,sizeof(MSG));
		printf("server>>%s\n",pmsg->info);
	}

	/*挂电话*/
	close(fd);
}

/*查询历史记录*/
void query_history(int fd,MSG* pmsg)
{
	pmsg->type = 'H';//命令类型：查询历史
	int cnt = 0;//记录服务器返回了多少次查询结果

	/*向服务器发送查询历史的命令*/
	write(fd,pmsg,sizeof(MSG));
	
	/*不断读取并打印服务器返回的查询结果*/
	usleep(500000);
	while(1)
	{
		read(fd,pmsg,sizeof(MSG));
		if(strncmp(pmsg->info,"OVER",4) == 0)
		{
			puts("");
			pmsg->type = 'X';//命令类型：结束服务器子线程，返回accept等待接听
			write(fd,pmsg,sizeof(MSG));
			close(fd);
			break;
		}
		
		printf("%-20s",pmsg->info);
		cnt++;
		if(cnt%3 == 0)
			puts("");//每3个字符串换一次行
		usleep(10000);
	}

	/*挂电话*/
	close(fd);
}

/*告诉服务器本机要退出程序*/
void query_exit(int fd,MSG* pmsg)
{
	pmsg->type = 'E';//命令类型：退出
	strcpy(pmsg->info,"Exit at once......");

	/*将用户信息发送给服务器*/
	write(fd,pmsg,sizeof(MSG));

	/*挂电话*/
	close(fd);
}


